<template>
    <div class="common-layout">
        <!-- 网页头导航 -->
        <el-container>
            <el-header class="common-header" style="box-shadow:var(--el-box-shadow-light);">
                <AllHead></AllHead>
            </el-header>
        </el-container>
        <el-main>
            <!-- 食谱取名 -->
            <el-form-item label="食谱：">
                <el-input v-model.trim="title" style="width: 20vw;height: 5vh;box-shadow: 0.5vw;" maxlength="20"
                    length="20" placeholder="食谱名" show-word-limit type="text" :validate-event="false" />
            </el-form-item>

            <!-- 选择食谱的菜系 -->
            <el-form-item label="菜系：">
                <el-select v-model.number="value" placeholder="菜系" size="large" style="width: 240px"
                    :validate-event="false">
                    <el-option v-for="c in getCuisines" :key="c.id" :label="c.name" :value="c.id" />
                </el-select>
            </el-form-item>

            <!-- 难度选择 -->
            <el-form-item label="难度：" prop="degree">
                <el-rate v-model="degree" class="degree" void-color="red" />
            </el-form-item>

            <!-- 菜谱描述 -->
            <el-form-item label="介绍：">
                <el-input v-model.trim="cookDescription" style="width: 360px;" maxlength="300" placeholder="食谱描述"
                    show-word-limit type="textarea" :validate-event="false" autosize />
            </el-form-item>



            <!-- 添加厨具 -->
            <el-form-item class="Additem" v-for="(cooker, index) in dynamicCookerdateForm.cookers" :key="cooker.key"
                :label="'厨具' + (index + 1)" :prop="'cookers.' + index + '.value'" style="margin-bottom: 0;">

                <el-input v-model.trim="cooker.name" style="width: 540px;height: 40px;" maxlength="30"
                    placeholder="厨具名称" show-word-limit type="text" :validate-event="false" />
                <el-input-number v-model.number="cooker.quantity" :min="1" :validate-event="false"
                    style="height: 40px" />
                <el-button class="mt-2" @click.prevent="removeCooker(cooker)" style="height: 40px;">
                    删除
                </el-button>
            </el-form-item>
            <el-button @click="addCooker">新厨具</el-button><br>



            <!-- 添加食材 -->
            <el-form-item class="Additem" v-for="(food, index) in dynamicFooddateForm.foods" :key="food.key"
                :label="'食材' + (index + 1)" :prop="'foods.' + index + '.value'" style="margin-bottom: 0;">

                <el-input v-model.trim="food.name" style="width: 540px;height: 40px;height: 40px" maxlength="30"
                    placeholder="食材名称" show-word-limit type="text" />
                <el-select v-model.number="food.category" placeholder="食材" required style="width: 80px;" size="large">
                    <el-option v-for="item in food.fooptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
                <el-input-number v-model.number="food.quantity" :min="1" style="height: 40px" size="" />
                <el-select v-model.number="food.unit" placeholder="重量" required style="width: 80px" size="large">
                    <el-option v-for="item in food.massoptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
                <el-button class="mt-2" @click.prevent="removeFood(food)" style="height: 40px;">
                    删除
                </el-button>
            </el-form-item>
            <el-button @click="addFood">新食材</el-button><br>


            <!-- 添加步骤 -->
            <el-form-item class="Additem" v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key"
                :label="'步骤' + (index + 1)" :prop="'domains.' + index + '.value'" style="margin-bottom: 0;">
                <el-input v-model.trim="domain.title" maxlength="30" placeholder="步骤标题" show-word-limit type="text"
                    class="elTitle" style="width: 540px;height: 40px" />

                <el-input-number v-model.number="domain.timeRequired" :min="1" size="large"
                    style="height: 40px;width: 150px;" />
                <el-select v-model.number="domain.timeUnit" placeholder="时间" required style="width: 80px;" size="large">
                    <el-option v-for="item in domain.timeoptions" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
                <el-input v-model.trim="domain.description" style="width: 540px;" maxlength="300" placeholder="步骤描述"
                    show-word-limit type="textarea" :autosize="{ minRows: 8, maxRows: 16 }" />
                <el-button class="mt-2 desDelete" @click.prevent="removeDomain(domain)" style="height: 40px;">
                    删除
                </el-button>



                <!--  -->

                <label for="userimg">
                    <el-link underline="never" class="link">
                        <el-image :src="imgSrc" class="userImg" @mouseenter="userImgHover"></el-image>
                        <div v-show="showChangeImg" class="userImg hoverShow" @mouseleave="uesrImgLeave">添加图片</div>

                        <!-- <img :src="imgSrc" width="200px" class="userImg"> -->
                    </el-link>
                </label>
                <input type="file" id="userimg" @change="changeImg($event)" accept="image/*" >
                <!-- <el-upload v-model:file-list="fileList[index]" :on-preview="handlePictureCardPreview" action="/api/image/upload" list-type="picture-card" :limit="1"
                    :on-remove="handleRemove" :on-success="handleSuccess" :headers="{ 'Content-Type': 'multipart/form-data' }">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload> -->

                <!-- <el-upload v-model:file-list="fileList[index]" :limit="1" :on-success="handleSuccess"
                    action="#" 
                    list-type="picture-card"
                     :on-preview="handlePictureCardPreview" 
                     :data="{ file:fileList[index], type: 'cooking' }"
                    :on-remove="handleRemove" 
                    >
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog> -->


                <!--  -->






            </el-form-item>
            <el-button @click="addDomain">新步骤</el-button><br>

            <!-- 小贴士 -->
            <el-form-item>
                <el-input v-model.trim="tips" maxlength="30" placeholder="小贴士" show-word-limit type="text"
                    class="elTitle" style="width: 540px;height: 40px" />
            </el-form-item>





            <!-- 最后的人数与发布 -->
            <el-input-number label="人数" v-model.number="servings" :min="1" style="height: 40px" />
            <el-button type="primary" @click="sendRecipe" :plain="true" class="sengBut">发布食谱</el-button>
        </el-main>
    </div>
</template>

<script setup lang="ts">
import { Bottom } from '@element-plus/icons-vue';
import AllHead from './AllHead.vue';
import axios from 'axios'
import { ElMessage, type FormInstance, type FormRules, } from 'element-plus';
import { reactive, ref, nextTick, watch } from 'vue'
import type { UploadFile, UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
//-----------------------------------------------
let imgSrc = ref('')//记得改回用户修改图片
async function changeImg(e: any) {
    const fd = new FormData()
    // 往formData中添加参数
    fd.append('file', e.target.files[0])
    if (e.target.files[0] == undefined) {
        return
    }
    axios({
        url: '/api/image/upload',
        method: 'post',
        data: {
            file: e.target.files[0],
            type: 'cooking'
        },
        // 传输图片专属头
        headers: { 'Content-Type': 'multipart/form-data', }

    }).then(res => {
        console.log(res.data.data);

        imgSrc.value = 'http://' + res.data.data
    })
}

let showChangeImg = ref(false)
function userImgHover() {
    showChangeImg.value = true
}
function uesrImgLeave() {
    showChangeImg.value = false
}
// const dialogImageUrl = ref('')
// const dialogVisible = ref(false)
// // const fileList = ref<UploadFile[]>([]);
// interface CustomFile extends UploadUserFile {
//     serverId?: string // 自定义类型：记录服务端返回的文件ID
// }

// const fileList = ref<CustomFile[]>([])

// const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
//     if (!response) return
//     (uploadFile as CustomFile).serverId = 'http://' + response.data.data // 假设后端返回 { data: { id: 'xxx' } }
//     console.log(response.data.data)
// }


// const handleRemove: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
//     try {
//         // 1. 调用后端删除接口
//         // await axios.delete(`/api/image/delete/`)

//         // 2. 成功提示（可选）
//         ElMessage.success('删除成功')

//         // 3. 前端自动同步（el-upload 会自动更新 fileList）
//     } catch (err) {
//         // 4. 处理删除失败（关键！需要还原文件列表）
//         ElMessage.error('删除失败，请重试')

//         // 5. 恢复被删除的文件到列表（根据业务需求选择）
//         fileList.value = [...fileList.value, uploadFile]
//     }
// }
// const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
//     dialogImageUrl.value = uploadFile.url!
//     dialogVisible.value = true
// }

//-----------------------------------------------
const degree = ref(4)//制作难度

let title = ref('番茄炒蛋')//标题
let cookDescription = ref('好吃')//食谱描述

let value = ref()
let getCuisines: cuisine[] = reactive([])
// 先拿到食谱类型列表
cuiList()
async function cuiList() {
    const List = await axios({
        url: '/api/board/queryBoardList',
    })
    Object.assign(getCuisines, List.data.data)
}

// element-plus组件写法，厨具对象数组
const dynamicCookerdateForm = reactive<{
    cookers: CookerItem[]
}>({//先设置厨具第一个的初始值为空，也是便于用户填写
    cookers: [{ key: 1, value: null, name: '刀', quantity: 1, cuisines: getCuisines }],
})
interface cuisine {
    description: string
    id: number
    name: string
    recipedegree: number
    updateTime: string
}
interface CookerItem {
    key: number
    value: any
    name: string
    quantity: number
    cuisines: cuisine[]
}
// 删除厨具操作·1
const removeCooker = (item: CookerItem) => {
    const index = dynamicCookerdateForm.cookers.indexOf(item)//先拿到需要删除厨具数组的index
    if (dynamicCookerdateForm.cookers.length !== 1) {//如果只剩一个厨具，也就是数组只剩一位，则不能删除
        // splice就是删除index开始的第一个元素
        dynamicCookerdateForm.cookers.splice(index, 1)
    }
}
// 添加厨具
const addCooker = () => {
    dynamicCookerdateForm.cookers.push({
        // 设置默认值
        key: Date.now(),
        value: null,
        name: '',
        quantity: 1,
        cuisines: getCuisines
    })
}





// 步骤
const dynamicValidateForm = reactive<{
    domains: DomainItem[]
}>({
    domains: [{ imgSrc: 'abc', stepNumber: 1, key: 1, description: '慢慢来', title: '准备食材', timeRequired: 1, timeUnit: 1, timeoptions: [{ label: '秒', value: 1, }, { label: '分', value: 2, }, { label: '时', value: 3, }, { label: '天', value: 4, }] }],//步骤描述
})
// 步骤对象接口
interface timeOption {
    label: string
    value: number
}
interface DomainItem {
    key: number
    description: string
    title: string
    timeRequired: number
    timeUnit: any
    stepNumber: number
    imgSrc: string
    timeoptions: timeOption[]
}
const removeDomain = (item: DomainItem) => {//同理厨具的描述
    const index = dynamicValidateForm.domains.indexOf(item)
    if (dynamicValidateForm.domains.length !== 1) {
        dynamicValidateForm.domains.splice(index, 1)
    }
}
const addDomain = () => {
    dynamicValidateForm.domains.push({
        key: Date.now(),
        imgSrc: '',
        description: '',
        title: '',
        timeRequired: 1,
        timeUnit: 1,//默认初始为‘秒’
        stepNumber: dynamicValidateForm.domains.length,
        timeoptions: [{ label: '秒', value: 1, }, { label: '分', value: 2, }, { label: '时', value: 3, }, { label: '天', value: 4, }]
    })
}







// 食材
const dynamicFooddateForm = reactive<{
    foods: FoodsItem[]
}>({//默认料理类型为主料，食材重量单位为克
    foods: [{ key: 1, category: 1, name: '盐', quantity: 1, unit: 1, fooptions: [{ label: '主料', value: 1, }, { label: '辅料', value: 2, }, { label: '调料', value: 3, }], massoptions: [{ label: '克', value: 1, }, { label: '千克', value: 2, }, { label: '毫升', value: 3, }, { label: '升', value: 4, }] }],//每个食材
})
// 食材对象接口
interface foodOption {
    label: string
    value: number
}
interface massOption {
    label: string
    value: number
}
interface FoodsItem {
    key: number
    category: any
    name: string
    quantity: number
    unit: any
    fooptions: foodOption[]
    massoptions: massOption[]
}
// 删除食材
const removeFood = (item: FoodsItem) => {//同理上面的
    const index = dynamicFooddateForm.foods.indexOf(item)
    if (dynamicFooddateForm.foods.length !== 1) {
        dynamicFooddateForm.foods.splice(index, 1)
    }
}
// 添加食材
const addFood = () => {
    dynamicFooddateForm.foods.push({
        key: Date.now(),
        category: 1,
        name: '',
        quantity: 1,
        unit: 1,
        fooptions: [{ label: '主料', value: 1, }, { label: '辅料', value: 2, }, { label: '调料', value: 3, }],
        massoptions: [{ label: '克', value: 1, }, { label: '千克', value: 2, }, { label: '毫升', value: 3, }, { label: '升', value: 4, }]
    })
}


// 判断填写完成读度
let servings = ref(1)
function Judge() {
    if (title.value == '') {
        return '请填写食谱名称'
    }
    if (value.value == undefined) {
        return '请选择菜系'
    }
    if (degree.value == undefined) {
        return '请选择制作难度'
    }
    for (let cooker of dynamicCookerdateForm.cookers) {
        if (cooker.name == '') {
            return '请填写厨具名称'
        }
    }
    for (let domain of dynamicValidateForm.domains) {
        if (domain.title == '' || domain.description == '' || domain.timeUnit == undefined) {
            return '请填满每一个步骤信息'
        }
    }
    if (cookDescription.value == '') {
        return '请对食谱进行简要描述'
    }
    for (let food of dynamicFooddateForm.foods) {
        if (food.category == undefined || food.unit == undefined || food.name == '') {
            return '请填满每一个食材信息'
        }
    }
}

// 小提示
let tips = ref('记得放盐')

// 发送食谱
async function sendRecipe() {
    let error = Judge()
    if (!error) {
        let JsonObj = reactive({
            boardId: value.value,
            cookerDTOS: dynamicCookerdateForm.cookers,
            cookingDTOS: dynamicValidateForm.domains,
            coverImage:'dsfsf',
            description: cookDescription.value,
            difficulty: degree.value,
            materialDTOS: dynamicFooddateForm.foods,
            name: title.value,
            servings: servings.value,
            tips: tips.value,
            
        })
        for (let [key, val] of Object.entries(JsonObj)) {
            console.log(key, val);//打印每个需要发送数据，便于测试
        }
        await axios({
            url: '/api/recipe/add',
            method: 'post',
            data: JSON.stringify(JsonObj),
            headers: { 'Content-Type': 'application/json' }
        })
        // 弹出发布成功
        ElMessage({
            message: '发布成功',
            type: 'success',
            plain: true,
        })
        return
    }
    // 弹出发布失败
    ElMessage({
        message: error,
        type: 'error',
        plain: true,
    })
}





</script>

<style scoped>
.common-layout {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #FFF9F0;
}

.common-header {
    position: fixed;
    z-index: 999;
    height: 10vh;
    width: 100%;
    background: #FFF9F0;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-main {
    padding-top: 100px;
    padding-left: 20vw;
    padding-right: 20vw;
    background-color: #FFFCF5;
}

/* 表单卡片样式 */
.el-form-item {
    margin-top: 24px;
    margin-bottom: 0;
    background: white;
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.el-form-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.el-form-item__label {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    display: block;
}

/* 基础表单元素 */
.el-input,
.el-select,
.el-textarea {
    font-size: 1vw;
    width: 100%;
    max-width: 600px;
    transition: all 0.3s ease;
}

.el-input:hover,
.el-select:hover,
.el-textarea:hover {
    border-color: #FF8C42;
}

/* 动态添加的项目卡片 */
.Additem {
    background: white;
    padding: 24px;
    border-radius: 12px;
    margin-bottom: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #FFE8CC;
    transition: all 0.3s ease;
}

.Additem:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    border-color: #FF8C42;
}

/* 按钮样式 */
.el-button {
    margin-right: 12px;
    transition: all 0.3s ease;
    border-radius: 8px;
}

.el-button--primary {
    background-color: #FF6B35;
    border-color: #FF6B35;
}

.el-button--primary:hover {
    background-color: #FF8C42;
    border-color: #FF8C42;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 107, 53, 0.3);
}

/* 难度评分 */
.degree {
    margin-top: 8px;
}

.el-rate__icon {
    font-size: 28px;
}

/* 布局调整 */
.el-form-item__content {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.el-form-item__content>* {
    margin-bottom: 0 !important;
}


:deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #ccc inset;
    /* 蓝色边框，2px 宽度 */
    box-shadow: 0 0 0 1px #ccc inset;
    /* 蓝色边框，2px 宽度 */
}


:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 2px #FF6B35 inset !important;
    /* 聚焦时绿色边框 */
}

.sengBut {
    color: white;
}
.userImg {
  width: 300px;
  height: 250px;
  /* border-radius: 50%; */
  border: 3px solid #FFE8CC;
  object-fit: cover;
  transition: all 0.3s ease;
}

.userImg:hover {
  transform: scale(1.05);
}
.link{
  position: relative;
}
.hoverShow{
  width: 290px;
  height: 240px;
  text-align: center;
  line-height: 115px;
  position: absolute;
  background-color: rgba(0, 0, 0, 0.1);
}
#userimg{
    display: none;
}
</style>
